package com.chinawlx.wlxteacher.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.base.WLXApplication;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXGetCodeBean;
import com.chinawlx.wlxteacher.network.bean.WLXLoginBean;
import com.chinawlx.wlxteacher.network.bean.WLXStudentBean;
import com.chinawlx.wlxteacher.utils.TimerCountUtil;
import com.chinawlx.wlxteacher.utils.ToPinyinUtils;
import com.chinawlx.wlxteacher.utils.WLXActivityManagerUtil;
import com.chinawlx.wlxteacher.utils.WLXAnimationUtil;
import com.chinawlx.wlxteacher.utils.WLXConstant;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.utils.WLXMD5Util;
import com.chinawlx.wlxteacher.utils.WLXNetUtil;
import com.chinawlx.wlxteacher.utils.WLXSharedPreferenceUtil;
import com.chinawlx.wlxteacher.wlx_auth;
import com.chinawlx.wlxteacher.wlx_authDao;
import com.chinawlx.wlxteacher.wlx_student;
import com.chinawlx.wlxteacher.wlx_studentDao;
import com.chinawlx.wlxteacher.wlx_student_order_detail;
import com.chinawlx.wlxteacher.wlx_student_order_detailDao;
import com.chinawlx.wlxteacher.wlx_user;
import com.chinawlx.wlxteacher.wlx_userDao;
import com.google.gson.Gson;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;


/**
 * 作者:吴名
 * 时间:16/8/1
 * 描述:登陆页面
 */
public class WLXLoginActivity extends WLXBaseActivity {

    @BindView(R.id.et_login_phone)
    EditText mEtLoginPhone;
    @BindView(R.id.tv_login_getcode)
    TextView mTvLoginGetcode;
    @BindView(R.id.et_login_code)
    EditText mEtLoginCode;
    @BindView(R.id.btn_login_login)
    Button mBtnLoginLogin;
    @BindView(R.id.iv_login_about)
    ImageView mIvLoginAbout;
    @BindView(R.id.viewFlipper)
    ViewFlipper mViewFlipper;
    @BindView(R.id.iv_upglide)
    ImageView mIvUpglide;


    /**
     * 手机按下时的坐标位置
     */
    private float startY;
    private AnimationDrawable mAnimationDrawable;
    private Context mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mContext = this;
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        WLXActivityManagerUtil.addActivity(this);

        if ((boolean) WLXSharedPreferenceUtil.get(mContext, WLXConstant.KEY_IS_FIRST_LAUCH,
                true)) {
            mViewFlipper.setVisibility(View.VISIBLE);
            mIvUpglide.setVisibility(View.VISIBLE);

            //显示引导页
            mAnimationDrawable = (AnimationDrawable) mIvUpglide.getDrawable();//上滑箭头动画
            mAnimationDrawable.start();
        } else {
            mViewFlipper.setVisibility(View.GONE);
            mIvUpglide.setVisibility(View.GONE);
        }
        initListener();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if ((boolean) WLXSharedPreferenceUtil.get(mContext, WLXConstant.KEY_IS_FIRST_LAUCH,
                true)) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    startY = event.getY();
                    break;
                case MotionEvent.ACTION_UP:
                    float endY = event.getY();
                    if (startY > endY) {
                        //手指上滑,显示下一个
                        if (mViewFlipper.getDisplayedChild() != mViewFlipper.getChildCount() - 1) {
                            mAnimationDrawable.stop();
                            mIvUpglide.setVisibility(View.GONE);
                            mViewFlipper.setInAnimation(this, R.anim.anim_from_down_in);
                            mViewFlipper.setOutAnimation(this, R.anim.anim_from_up_out);
                            mViewFlipper.showNext();
                        }
                    } else if (startY < endY) {
                        //手指下滑,显示上一个
                        if (mViewFlipper.getDisplayedChild() != 0) {
                            mAnimationDrawable.stop();
                            mIvUpglide.setVisibility(View.GONE);
                            mViewFlipper.setInAnimation(this, R.anim.anim_from_up_in);
                            mViewFlipper.setOutAnimation(this, R.anim.anim_from_down_out);
                            mViewFlipper.showPrevious();
                        }
                    }
                    if (mViewFlipper.getDisplayedChild() == mViewFlipper.getChildCount() - 1) {
                        //显示最后一个引导页时,隐藏向上滑动箭头
                        mAnimationDrawable.stop();
                        mIvUpglide.setVisibility(View.GONE);

                        //引导页消失,显示登录
                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Animation animation = WLXAnimationUtil.createZoomInAwayAnim();
                                animation.setFillAfter(true);
                                mViewFlipper.startAnimation(animation);
                                animation.setAnimationListener(new Animation.AnimationListener() {
                                    @Override
                                    public void onAnimationStart(Animation animation) {

                                    }

                                    @Override
                                    public void onAnimationEnd(Animation animation) {
                                        WLXSharedPreferenceUtil.put(mContext, WLXConstant
                                                .KEY_IS_FIRST_LAUCH, false);
                                        mViewFlipper.setVisibility(View.GONE);
                                    }

                                    @Override
                                    public void onAnimationRepeat(Animation animation) {

                                    }
                                });

                            }
                        }, 1000);

                    } else {
                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mAnimationDrawable.start();
                                mIvUpglide.setVisibility(View.VISIBLE);
                            }
                        }, getResources().getInteger(R.integer.anim_time_flipper) + getResources
                                ().getInteger(R.integer.anim_time_upglide) - 250);
                    }
                    break;
            }
        }
        return super.onTouchEvent(event);
    }

    private void initListener() {
        mTvLoginGetcode.setClickable(false);
        //监听手机号码输入
        mEtLoginPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().trim().length() == 11) {
                    mTvLoginGetcode.setClickable(true);
                    mTvLoginGetcode.setBackgroundResource(R.drawable.shape_login_getcode);
                    mTvLoginGetcode.setTextColor(getResources().getColor(R.color
                            .login_bg_blue));
                } else {
                    mTvLoginGetcode.setClickable(false);
                    mTvLoginGetcode.setBackgroundResource(R.drawable
                            .shape_login_getcode_inconformity);
                    mTvLoginGetcode.setTextColor(getResources().getColor(android.R.color.white));
                }

                if (mEtLoginPhone.getText() != null && mEtLoginCode.getText() != null &&
                        mEtLoginPhone.getText().toString().trim().length() == 11 && mEtLoginCode
                        .getText().toString().trim().length()
                        > 0) {
                    mBtnLoginLogin.setTextColor(getResources().getColor(android.R.color.white));
                    mBtnLoginLogin.setClickable(true);
                } else {
                    mBtnLoginLogin.setTextColor(getResources().getColor(R.color
                            .gray_item));
                    mBtnLoginLogin.setClickable(false);
                }
            }
        });
        //监听短信验证码输入
        mEtLoginCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (mEtLoginPhone.getText() != null && mEtLoginCode.getText() != null &&
                        mEtLoginPhone.getText().toString().trim().length() == 11 && mEtLoginCode
                        .getText().toString().trim().length()
                        > 0) {
                    mBtnLoginLogin.setTextColor(getResources().getColor(android.R.color.white));
                    mBtnLoginLogin.setClickable(true);
                } else {
                    mBtnLoginLogin.setTextColor(getResources().getColor(R.color
                            .gray_item));
                    mBtnLoginLogin.setClickable(false);
                }
            }
        });
    }

    @OnClick({R.id.tv_login_getcode, R.id.btn_login_login, R.id.iv_login_about})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login_getcode://获取验证码
                TimerCountUtil timerCountUtil = new TimerCountUtil(30 * 1000, 1 * 1000,
                        mTvLoginGetcode, R.drawable.shape_login_getcode_inconformity, R.drawable
                        .shape_login_getcode, android.R.color.white, R.color.login_bg_resend_text_blue);
                timerCountUtil.start();
                if (WLXNetUtil.CheckNetwork(WLXApplication.myApplication)) {
                    String mobile = mEtLoginPhone.getText().toString().trim();
                    String type_code = "login";
                    String timestamp = WLXDateUtil.getCurrentTime();
                    String sign = WLXConstant.APISECRET + "mobile" + mobile + "timestamp" +
                            timestamp +
                            "type_code" + type_code + WLXConstant.APISECRET;
                    String signMD5 = WLXMD5Util.parseStrToMd5U32(sign);
                    WLXHttpRxHelper.getInstance().getCode(mobile, type_code, timestamp, signMD5,
                            new Subscriber<WLXGetCodeBean>() {
                                @Override
                                public void onCompleted() {


                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(WLXGetCodeBean wlxGetCodeBean) {

                                    if (wlxGetCodeBean.getCode() != 0) {
                                        Toast.makeText(WLXLoginActivity.this, wlxGetCodeBean.getMsg(),
                                                Toast.LENGTH_LONG);
                                    }

                                }
                            });
                } else {
                    Toast.makeText(WLXLoginActivity.this, "无网络", Toast.LENGTH_LONG).show();

                }
                break;
            case R.id.btn_login_login://登录
                if (WLXNetUtil.CheckNetwork(WLXApplication.myApplication)) {
                    String mobile_login = mEtLoginPhone.getText().toString().trim();
                    String code = mEtLoginCode.getText().toString().trim();
                    String timestamp_login = WLXDateUtil.getCurrentTime();
                    String sign_login = WLXConstant.APISECRET + "code" + code + "mobile" +
                            mobile_login + "timestamp" + timestamp_login + WLXConstant.APISECRET;
                    String signMD5_login = WLXMD5Util.parseStrToMd5U32(sign_login);

                    WLXHttpRxHelper.getInstance().login(code, mobile_login, timestamp_login,
                            signMD5_login, new Subscriber<WLXLoginBean>() {
                                @Override
                                public void onCompleted() {
                                    requestNet();
                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(WLXLoginBean loginBean) {
                                    if (loginBean.getCode() == 0) {
                                        String mobile = loginBean.getData().getUser().getMobile();
                                        String nickname = loginBean.getData().getUser().getProfile()
                                                .getNickname();
                                        String realname = loginBean.getData().getUser().getProfile()
                                                .getRealname().getName();
                                        String birthday = loginBean.getData().getUser().getProfile()
                                                .getBirthday();
                                        String avatar_url = loginBean.getData().getUser()
                                                .getProfile()
                                                .getAvatar().getUrl();
                                        String qq = loginBean.getData().getUser().getProfile()
                                                .getQq();
                                        int level = loginBean.getData().getUser().getProfile()
                                                .getLevel()
                                                .getLevel();
                                        int score = loginBean.getData().getUser().getProfile()
                                                .getLevel()
                                                .getScore();
                                        String sex_code = loginBean.getData().getUser().getProfile()
                                                .getSex().getValue();
                                        String user_type_code = loginBean.getData().getUser()
                                                .getProfile
                                                        ().getUser_type().getValue();
                                        String last_modified_date = loginBean.getData().getUser()
                                                .getProfile().getLast_modified_date();

                                        //存储Cookie
                                        WLXConstant.IS_ACTIVE = loginBean.getData().getUser()
                                                .getProfile
                                                        ().isIs_actived() ? 1 : 0;
                                        WLXConstant.USER_ID = Integer.toString(loginBean.getData().getUser().getId());
                                        String cookieStr = new Gson().toJson(WLXConstant
                                                .cookieStore);
                                        //---------存储wlx_auth表----------
                                        List<wlx_auth> authList = WLXGreenDaoUtil.getAuthDao()
                                                .queryBuilder().where(wlx_authDao.Properties
                                                        .User_id.eq(WLXConstant.USER_ID)).list();
                                        if (authList.size() > 0) {
                                            wlx_auth auth = authList.get(0);
                                            auth.setCookie(cookieStr);
                                            auth.setIs_active(WLXConstant.IS_ACTIVE);
                                            auth.setLast_modified_date(WLXDateUtil
                                                    .getStringToDate(last_modified_date));
                                            WLXGreenDaoUtil.getAuthDao().update(auth);
                                        } else {

                                            WLXGreenDaoUtil.getAuthDao().insert(new wlx_auth
                                                    (WLXConstant
                                                            .USER_ID+"", cookieStr, WLXConstant.VERSION,
                                                            WLXConstant
                                                                    .IS_ACTIVE, WLXDateUtil.getStringToDate
                                                            (last_modified_date)));
                                        }


                                        //----------------存储wlx_user表---------------------
                                        wlx_user wlxUser = new wlx_user(WLXConstant.USER_ID+"", mobile,
                                                nickname, realname, WLXDateUtil.getStringToDate
                                                (birthday)
                                                , avatar_url, qq, level, score, sex_code,
                                                user_type_code,
                                                WLXDateUtil.getStringToDate(last_modified_date));
                                        //1,查询user_id这条记录,user_id是唯一的
                                        List<wlx_user> list = WLXGreenDaoUtil.getUserDao()
                                                .queryBuilder()
                                                .where(wlx_userDao.Properties.User_id.eq(WLXConstant
                                                        .USER_ID)).list();
                                        if (list.size() > 0) {
                                            WLXLogUtil.printE("user查询到的指定id记录信息:" + list.get(0)
                                                    .toString());
                                            //2, 有这条记录, 就去对比last_modified_date, 如果服务器时间更新, 就update表数据
                                            if (WLXDateUtil.getStringToDate(last_modified_date) >
                                                    list
                                                            .get(0).getLast_modified_date()) {
                                                WLXGreenDaoUtil.getUserDao().update(wlxUser);
                                            }
                                        } else {
                                            //无数据,就直接插入数据
                                            WLXGreenDaoUtil.getUserDao().insert(wlxUser);
                                        }
                                        //-----------------------------------------------
                                        startActivity(WLXCourseOrClazzActivity.class);
                                        WLXLoginActivity.this.finish();
                                    } else {
                                        Toast.makeText(WLXLoginActivity.this, loginBean.getMsg(),
                                                Toast
                                                        .LENGTH_LONG).show();
                                    }
                                }
                            });
                } else {
                    Toast.makeText(WLXLoginActivity.this, "无网络", Toast.LENGTH_LONG).show();
                }


                break;
            case R.id.iv_login_about://关于未来星
                Uri uri = Uri.parse("http://www.chinawlx.com");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                break;
        }
    }
    private void requestNet() {
        //        -----------------获取学生列表--------------------
        WLXHttpRxHelper.getInstance().getStudentList(new Subscriber<WLXStudentBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(WLXStudentBean studentBean) {
                //------------------------------wlx_students表--------------------------------
                List<WLXStudentBean.DataBean.StudentListBean> student_list = studentBean.getData
                        ().getStudent_list();
                for (WLXStudentBean.DataBean.StudentListBean studentListBean : student_list) {
                    String student_id = Integer.toString(studentListBean.getId());
                    int family_user_id = studentListBean.getFamily_user_id();
                    String realname = studentListBean.getRealname();
                    String realname_pinyin = ToPinyinUtils.getPinYin(realname);
                    long birthday = WLXDateUtil.getStringToDate(studentListBean.getBirthday());
                    String mobile = studentListBean.getMobile();
                    String avatar_url = studentListBean.getAvatar().getUrl();
                    String remark = studentListBean.getRemark();
                    String sex_code = studentListBean.getSex().getKey();
                    long last_modified_date = WLXDateUtil.getStringToDate(studentListBean
                            .getLast_modified_date());
                    wlx_student wlx_student = new wlx_student(student_id, family_user_id,
                            realname, realname_pinyin, birthday, mobile, avatar_url, remark,
                            sex_code, last_modified_date);
                    List<wlx_student> wlx_students = WLXGreenDaoUtil.getStudentDao().queryBuilder
                            ().where(wlx_studentDao.Properties.Student_id.eq(student_id)).list();
                    if (wlx_students.size() > 0) {
                        if (last_modified_date > wlx_students.get(0).getLast_modified_date()) {
                            WLXGreenDaoUtil.getStudentDao().update(wlx_student);
                        }
                    } else {
                        WLXGreenDaoUtil.getStudentDao().insert(wlx_student);
                    }
                }
                //----------------------------wlx_student_order_detail表----------------------------
                List<WLXStudentBean.DataBean.OrderDetailListBean> order_detail_list = studentBean
                        .getData().getOrder_detail_list();
                for (WLXStudentBean.DataBean.OrderDetailListBean detailListBean :
                        order_detail_list) {
                    String student_order_detail_id = Integer.toString(detailListBean.getId());
                    int student_id = detailListBean.getStudent_id();
                    int teacher_user_id = detailListBean.getTeacher_user_id();
                    int family_user_id = detailListBean.getFamily_user_id();
                    int org_user_id = detailListBean.getOrg_user_id();
                    int space_id = detailListBean.getSpace_id();
                    int classroom_id = detailListBean.getClassroom_id();
                    int grade_id = detailListBean.getGrade_id();
                    String grade_title = detailListBean.getGrade_title();
                    int medal_count = detailListBean.getMedal_count();
                    int homework_count = detailListBean.getHomework_count();
                    String grade_type_code = detailListBean.getGrade_type().getKey();
                    String grade_type_name = detailListBean.getGrade_type().getValue();
                    String class_type_code = detailListBean.getClass_type().getCode();
                    String class_type_name = detailListBean.getClass_type().getName();
                    String class_child_type_code = detailListBean.getClass_child_type().getCode();
                    String class_child_type_name = detailListBean.getClass_child_type().getName();
                    int consume_number = detailListBean.getConsume_number();
                    int balance_number = detailListBean.getBalance_number();
                    int total_number = detailListBean.getTotal_number();
                    long last_modified_date = WLXDateUtil.getStringToDate(detailListBean
                            .getLast_modified_date());
                    wlx_student_order_detail wlx_student_order_detail = new
                            wlx_student_order_detail(student_order_detail_id, student_id,
                            teacher_user_id, family_user_id, org_user_id, space_id, classroom_id,
                            grade_id, grade_title, medal_count, homework_count, grade_type_code,
                            grade_type_name, class_type_code, class_type_name,
                            class_child_type_code, class_child_type_name, consume_number,
                            balance_number, total_number, last_modified_date);
                    List<wlx_student_order_detail> wlxStudentOrderDetails = WLXGreenDaoUtil
                            .getStudentOrderDetailDao().queryBuilder().where
                                    (wlx_student_order_detailDao.Properties
                                            .Student_order_detail_id.eq(student_order_detail_id))
                            .list();
                    if (wlxStudentOrderDetails.size() > 0) {
                        if (last_modified_date > wlxStudentOrderDetails.get(0)
                                .getLast_modified_date()) {
                            WLXGreenDaoUtil.getStudentOrderDetailDao().update
                                    (wlx_student_order_detail);
                        }
                    } else {
                        WLXGreenDaoUtil.getStudentOrderDetailDao().insert(wlx_student_order_detail);
                    }
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        WLXActivityManagerUtil.finishAllActivity();
    }
}
